﻿using System.Windows;
using System.Windows.Controls;

namespace SS.WPF.Toolkit.PropertyEditor
{
    using System;

    /// <summary>
    /// Assigned data templates dynamically to data object 
    /// </summary>
    public class PropertyTemplateSelector : DataTemplateSelector
    {
        #region Public Methods

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var property = item as Property;
            if (property == null)
            {
                return base.SelectTemplate(item, container);
            }
            var element = container as FrameworkElement;
            if (element == null)
            {
                return base.SelectTemplate(property.Value, container);
            }
            DataTemplate template = this.FindDataTemplate(property, element);
            return template;
        }

        #endregion

        #region Methods

        private static DataTemplate TryFindDataTemplate(FrameworkElement element, object dataTemplateKey)
        {
            object dataTemplate = element.TryFindResource(dataTemplateKey);
            if (dataTemplate == null)
            {
                dataTemplateKey = new ComponentResourceKey(typeof(PropertyEditor), dataTemplateKey);
                dataTemplate = element.TryFindResource(dataTemplateKey);
            }
            return dataTemplate as DataTemplate;
        }

        private DataTemplate FindDataTemplate(Property property, FrameworkElement element)
        {
            Type propertyType = property.PropertyType;

            DataTemplate template = TryFindDataTemplate(element, propertyType);

            while (template == null && propertyType.BaseType != null)
            {
                propertyType = propertyType.BaseType;
                template = TryFindDataTemplate(element, propertyType);
            }
            if (template == null)
            {
                template = TryFindDataTemplate(element, "default");
            }
            return template;
        }

        #endregion
    }
}
